package com.siblings.loan.ui.loan.fm

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.lib.base.utils.DensityUtils
import com.lib.base.utils.TitleBarUtil
import com.siblings.lib_baseadapter.SIBOnItemChildClickListener
import com.siblings.loan.R
import com.siblings.loan.config.SibConfigs
import com.siblings.loan.databinding.FmLoanCommonBinding
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.status.StatusRepository
import com.siblings.loan.ui.loan.adapter.SibLoanAccountAdapter
import com.siblings.loan.ui.loan.adapter.SibLoanAppsAdapter
import com.siblings.loan.ui.loan.impl.SibLoanCommonPresenterImpl
import com.siblings.loan.ui.loan.view.ISibLoanCommonView
import com.siblings.loan.ui.tab.act.SibMainAct
import com.siblings.loan.ui.user.act.SibMessageAct
import com.siblings.loan.utils.decoration.LinearSpacingItemDecoration
import com.siblings.loan.utils.dialog.BindCardAddDialog
import com.siblings.loan.utils.dialog.BindCardDeleteDialog
import com.siblings.loan.utils.dialog.BindCardOnlyOneWarningDialog
import com.siblings.loan.utils.dialog.BindCardOtherDialog
import com.siblings.loan.utils.event.SibEventData
import com.siblings.loan.utils.event.SibEventType
import com.siblings.mvp.MvpFm
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/8 18:12
 * @Annotation：贷款通用（审核中、放款中、已拒绝）
 */
class SibLoanCommonFm(val obj: JSONObject): MvpFm<ISibLoanCommonView,SibLoanCommonPresenterImpl>(),ISibLoanCommonView {
    lateinit var binding: FmLoanCommonBinding
    var data = obj

    //账户列表
    private var accountAdapter: SibLoanAccountAdapter? = null
    //推荐APP列表
    private var appAdapter: SibLoanAppsAdapter? = null
    override fun getSibRootView(inflater: LayoutInflater): View {
        binding = FmLoanCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun createMvpPresenter(): SibLoanCommonPresenterImpl {
        return SibLoanCommonPresenterImpl(context)
    }

    override fun initSibView() {
        binding.parentLayout.setPadding(0,TitleBarUtil.getStatusBarHeight(),0,0)

        initSibRefreshLayout()
        initSibAccountRecyclerView()
        initSibAppRecyclerView()
    }

    override fun initSibListener() {
        //个人中心
        binding.imgMenu.setOnClickListener {
            val tabAct = context as SibMainAct
            tabAct.showSibMenuFragment(data.optString("eventRemark"))
        }
        //消息
        binding.imgMessage.setOnClickListener {
            onIntent(SibMessageAct::class.java)
        }
        //状态按钮
        binding.textStatus.setOnClickListener {
            showSibToast(binding.textStatus.text.toString())
        }
        //添加绑卡
        binding.addLayout.setOnClickListener {
            showSibBindCardDialog()
        }
    }

    override fun initSibData() {
        mvpPresenter.checkSibOrderOrApplyStatusAction(data)
    }

    /* 初始化刷新 */
    private fun initSibRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            EventBus.getDefault().post(SibEventData(SibEventData.TYPE.SIB_PROCESS_REFRESH))
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 初始化账户列表
     */
    private fun initSibAccountRecyclerView() {
        binding.rvAccount.setHasFixedSize(true)
        binding.rvAccount.isNestedScrollingEnabled = false
        binding.rvAccount.isFocusableInTouchMode = false //不需要焦点
        binding.rvAccount.layoutManager = LinearLayoutManager(context)
        val topDecoration = DensityUtils.dp2px(12f)
        binding.rvAccount.addItemDecoration(LinearSpacingItemDecoration(0,0,topDecoration,topDecoration))
        accountAdapter = SibLoanAccountAdapter(binding.rvAccount)
        binding.rvAccount.adapter = accountAdapter!!
        binding.rvAccount.itemAnimator = DefaultItemAnimator()
        accountAdapter!!.setOnItemChildClickListener { _, childView, position ->
            when(childView.id){
                R.id.deleteLayout -> {//删除
                    showSibDeleteDialog(position)
                }
            }
        }
    }

    /**
     * 初始化可安装App列表
     */
    private fun initSibAppRecyclerView() {
        binding.rvRecommended.setHasFixedSize(true)
        binding.rvRecommended.isNestedScrollingEnabled = false
        binding.rvRecommended.isFocusableInTouchMode = false //不需要焦点
        binding.rvRecommended.layoutManager = LinearLayoutManager(context)
        val topDecoration = DensityUtils.dp2px(12f)
        binding.rvRecommended.addItemDecoration(LinearSpacingItemDecoration(0,0,0,0))
        appAdapter = SibLoanAppsAdapter(binding.rvRecommended)
        binding.rvRecommended.adapter = appAdapter!!
        binding.rvRecommended.itemAnimator = DefaultItemAnimator()
        appAdapter!!.setOnItemChildClickListener(SIBOnItemChildClickListener { _, childView, position ->
            val item = appAdapter!!.getItem(position)
            if (childView.id == R.id.installLayout) {//点击安装
                HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_LOAN_AUDIT_RECOMMEND_APP_INSTALL,item.optString("appName"))
                val appLink = item.optString("appLink")
                if (appLink.isNotEmpty()){
                    val uri = Uri.parse(item.optString("appLink"))
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    startActivity(intent)
                }
            }
        })
    }

    /**
     * 状态改变，需要刷新页面
     */
    fun refreshView(data: JSONObject){
        this.data = data
        mvpPresenter.checkSibOrderOrApplyStatusAction(data)
//        mvpPresenter.loadCedLoanInfoAction()
//        loadAccountListAction()
//        loadRecommendAppAction()
    }

    /**
     * 显示放款中状态
     */
    override fun showSibLoanLendingView() {
        //获取已绑定账户列表
        mvpPresenter.loadSibLoanAccountAction()
        //获取评分配置
        mvpPresenter.loadSibScoreCommentAction()

        binding.vStatus.setBackgroundResource(R.drawable.sib_loan_status_lending_bg)
        binding.imgStatus.setImageResource(R.mipmap.pic_loan_status_lending)
        binding.textStatus.text = getString(R.string.loan_status_lending)
        binding.textStatus.setBackgroundResource(R.drawable.sib_loan_status_lending)

        binding.textLoanAmount.setTextColor(Color.parseColor("#FF000000"))
        binding.textReapply.visibility = View.GONE

        binding.accountLayout.visibility = View.VISIBLE
        binding.recommendedLayout.visibility = View.GONE
        binding.frenchTipsLayout.visibility = View.VISIBLE
        binding.auditTipsLayout.visibility = View.GONE
        //只有法语地区才显示添加账号按钮
        if (!SibConfigs.isFrench()){
            binding.addLayout.visibility = View.GONE
            binding.frenchTipsLayout.visibility = View.GONE
        }
    }

    /**
     * 显示审核中状态
     */
    override fun showSibLoanAuditView() {
        //获取已绑定账户列表
        mvpPresenter.loadSibLoanAccountAction()
        //获取评分配置
        mvpPresenter.loadSibScoreCommentAction()

        binding.vStatus.setBackgroundResource(R.drawable.sib_loan_status_audit_bg)
        binding.imgStatus.setImageResource(R.mipmap.pic_loan_status_audit)
        binding.textStatus.text = getString(R.string.loan_status_audit)
        binding.textStatus.setBackgroundResource(R.drawable.sib_loan_status_audit)

        binding.textLoanAmount.setTextColor(Color.parseColor("#FF000000"))
        binding.textReapply.visibility = View.GONE

        binding.accountLayout.visibility = View.VISIBLE
        binding.recommendedLayout.visibility = View.GONE
        binding.frenchTipsLayout.visibility = View.GONE
        binding.auditTipsLayout.visibility = View.GONE
        //只有法语地区才显示添加账号按钮
        if (!SibConfigs.isFrench()){
            binding.addLayout.visibility = View.GONE
        }

        //需要校验是否显示审核中提示
        mvpPresenter.checkSibAuditTipsShowStatus()
    }

    /**
     * 已拒绝（审核失败）
     */
    override fun showSibLoanFailedView() {
        //加载推荐APP列表
        mvpPresenter.loadSibRecommendAppAction()

        binding.vStatus.setBackgroundResource(R.drawable.sib_loan_status_failed_bg)
        binding.imgStatus.setImageResource(R.mipmap.pic_loan_status_failed)
        binding.textStatus.text = getString(R.string.loan_status_failed)
        binding.textStatus.setBackgroundResource(R.drawable.sib_loan_status_failed)

        binding.textLoanAmount.setTextColor(Color.parseColor("#FFEC3000"))
        binding.textReapply.visibility = View.VISIBLE
        binding.textReapply.text = String.format(getString(R.string.loan_reapply_after),data.optString("againApplyDate"))

        binding.accountLayout.visibility = View.GONE
        binding.recommendedLayout.visibility = View.VISIBLE
        binding.frenchTipsLayout.visibility = View.GONE
        binding.auditTipsLayout.visibility = View.GONE
    }

    /**
     * 审核中显示提示 Views
     */
    override fun showSibLoanAuditTipsView(obj: JSONObject) {
        binding.auditTipsLayout.visibility = View.VISIBLE
        binding.textAuditTipsTitle.text = obj.optString("auditTipsTitle")
        binding.textAuditTipsDesc.text = obj.optString("auditTipsDesc")
    }

    /**
     * 设置贷款信息
     */
    @SuppressLint("SetTextI18n")
    override fun showSibLoanInfoData(data: JSONObject) {
        binding.textLoanAmount.text = "${data.optString("amount")} ${data.optString("currency")}"
        binding.textLoanTerm.text = String.format(getString(R.string.loan_term_value),data.optString("days"))
    }

    /**
     * 设置已绑定的账户列表
     */
    override fun showSibLoanAccountList(list: ArrayList<JSONObject>) {
        accountAdapter!!.data = list

        /**
         * 法语地区 审核中 && 只有一个账户  提示新增绑卡
         */
        if (SibConfigs.isFrench()){
            //申请状态
            val applyStatus = data.optString("applyStatus")
            //审核中 && 只有一个账户
            if (StatusRepository(applyStatus).isReviewing() && list.size <= 1){
                showSibAccountOnlyOneAddDialog()
            }
        }
    }

    /**
     * 提示绑定另一个渠道账户
     */
    override fun showSibBingAccountOtherDialog(otherInfo: JSONObject) {
        val replaceDialog = BindCardOtherDialog(context,this.data.optString("eventRemark"),object : BindCardOtherDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btnRight){//添加
                    mvpPresenter.submitSibBindAccountAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        replaceDialog.setCancelable(true)
        replaceDialog.setCanceledOnTouchOutside(false)
        replaceDialog.show()
        replaceDialog.setBindAccountInfo(otherInfo)
    }

    /**
     * 设置推荐APP列表
     */
    override fun setSibRecommendAppList(list: ArrayList<JSONObject>) {
        appAdapter!!.data = list
    }

    /**
     * 法语地区 审核中 && 只有一个账户  提示新增绑卡
     */
    private fun showSibAccountOnlyOneAddDialog() {
        val dialog = BindCardOnlyOneWarningDialog(requireContext(),object : BindCardOnlyOneWarningDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btnAdd){
                    showSibBindCardDialog()
                }
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
    }

    /**
     * 添加绑卡dialog
     */
    private fun showSibBindCardDialog(){
        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_USER_ACCOUNT_ADD,this.data.optString("eventRemark"))
        val bindCardDialog = BindCardAddDialog(context,"StepAccount Page",object : BindCardAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                mvpPresenter.submitSibBindAccountAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(false)
        bindCardDialog.show()
    }


    /**
     * 删除提示
     */
    private fun showSibDeleteDialog(position: Int){
        val item = accountAdapter!!.getItem(position)
        item.put("walletLogo",item.optString("logo"))
        item.put("walletDesc",item.optString("name"))
        item.put("walletMobile",item.optString("account"))
        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_USER_ACCOUNT_DELETE,item.optString("cardId"))
        val deleteDialog = BindCardDeleteDialog(context,"StepAccount Page", object : BindCardDeleteDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btnRight){
                    mvpPresenter.deleteSibAccountAction(item.optString("cardId"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(false)
        deleteDialog.show()
        deleteDialog.setBindAccountInfo(item)
    }

    override fun hideSibLoading() {
        super.hideSibLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_LOAN_COMMON_START,this.data.optString("eventRemark"))
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_LOAN_COMMON__END,this.data.optString("eventRemark"))
    }
}